import 'package:sqflite/sqflite.dart';
import 'package:uuid/uuid.dart';

import '../../models/comment_model.dart';
import '../services/database_service.dart';

class CommentRepository {
  final DatabaseService _databaseService;
  final String _tableName = 'comments';

  CommentRepository(this._databaseService);

  Future<void> createTable(Database db) async {
    await db.execute('''
      CREATE TABLE $_tableName (
        id TEXT PRIMARY KEY,
        content TEXT NOT NULL,
        user_id TEXT NOT NULL,
        user_name TEXT NOT NULL,
        user_avatar TEXT NOT NULL,
        content_id TEXT NOT NULL,
        type INTEGER NOT NULL,
        like_count INTEGER DEFAULT 0,
        created_at TEXT NOT NULL
      )
    ''');
  }

  // 添加评论
  Future<CommentModel> addComment(CommentModel comment) async {
    final db = await _databaseService.database;

    final commentWithId =
        comment.id.isEmpty
            ? CommentModel(
              id: const Uuid().v4(),
              content: comment.content,
              userId: comment.userId,
              userName: comment.userName,
              userAvatar: comment.userAvatar,
              contentId: comment.contentId,
              type: comment.type,
              likeCount: comment.likeCount,
              createdAt: comment.createdAt,
            )
            : comment;

    await db.insert(
      _tableName,
      commentWithId.toJson(),
      conflictAlgorithm: ConflictAlgorithm.replace,
    );

    return commentWithId;
  }

  // 获取特定内容的所有评论
  Future<List<CommentModel>> getCommentsForContent(
    String contentId,
    CommentType type,
  ) async {
    final db = await _databaseService.database;
    final List<Map<String, dynamic>> maps = await db.query(
      _tableName,
      where: 'content_id = ? AND type = ?',
      whereArgs: [contentId, type.index],
      orderBy: 'created_at DESC',
    );

    return List.generate(maps.length, (i) => CommentModel.fromMap(maps[i]));
  }

  // 获取某用户的所有评论
  Future<List<CommentModel>> getCommentsForUser(String userId) async {
    final db = await _databaseService.database;
    final List<Map<String, dynamic>> maps = await db.query(
      _tableName,
      where: 'user_id = ?',
      whereArgs: [userId],
      orderBy: 'created_at DESC',
    );

    return List.generate(maps.length, (i) => CommentModel.fromMap(maps[i]));
  }

  // 更新评论
  Future<int> updateComment(CommentModel comment) async {
    final db = await _databaseService.database;
    return await db.update(
      _tableName,
      comment.toJson(),
      where: 'id = ?',
      whereArgs: [comment.id],
    );
  }

  // 删除评论
  Future<int> deleteComment(String commentId) async {
    final db = await _databaseService.database;
    return await db.delete(_tableName, where: 'id = ?', whereArgs: [commentId]);
  }

  // 点赞评论
  Future<int> likeComment(String commentId) async {
    final db = await _databaseService.database;

    // 先获取当前点赞数
    final List<Map<String, dynamic>> maps = await db.query(
      _tableName,
      columns: ['like_count'],
      where: 'id = ?',
      whereArgs: [commentId],
    );

    if (maps.isEmpty) {
      return 0;
    }

    final currentLikes = maps.first['like_count'] as int;
    final newLikes = currentLikes + 1;

    // 更新点赞数
    return await db.update(
      _tableName,
      {'like_count': newLikes},
      where: 'id = ?',
      whereArgs: [commentId],
    );
  }
}
